var TableColumnSetting = function () {
  var template = /* html */ `
    <div class="table-column-setting">
      <div v-for="(tableColumn,index) in tableColumns" :key="tableColumn.id" class="column-setting-item" :data-id="tableColumn.id">
        <div class="item-line" data-dir="top" ref="columnLine"></div>
        <div class="column-setting-item-content" ref="columnItem">
          <div class="column-item-index">
            <div style="width:80px;" class="column-item-colNo">第{{index+1}}列</div>
            <el-button size="small" type="danger" @click="delColumn(tableColumn.id)">删除</el-button>
          </div>
          <div class="column-item-content">
            <div class="flex">
              <div>
                <label>列名</label>
                <el-input v-model="tableColumn.label" size="small" class="column-input"></el-input>
              </div>
              <div style="margin-left:10px;">
                <label>宽度(px)</label>
                <el-input-number v-model="tableColumn.width" :min="0" :precision="0" controls-position="right"
                  size="small"></el-input-number>
              </div>
            </div>
            <div>
              <label>列显示内容</label>
              <el-select filterable v-model="tableColumn.field" size="small" class="column-input" @change="fieldChange(tableColumn)">
                <el-option v-for="dropdown in getColumnDropdown(tableColumn)" :key="'column_'+dropdown.field" :value="dropdown.field" 
                  :label="dropdown.label"></el-option>
              </el-select>
            </div>
            <div v-if="tableColumn.canSort">
              <el-checkbox v-model="tableColumn.hasSort">该列是否可以排序</el-checkbox>
            </div>
          </div>
        </div>
        <div class="item-line" data-dir="bottom" ref="columnLine"></div>
        <div class="item-hr"></div>
      </div>
      <div style="margin-top:10px" v-if="tableColumns.length<columnDropdown.length">
        <el-button size="small" type="primary" @click="addColumn">新增列</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      setting: {
        type: Object,
        required: true
      },

      columnField: {
        type: String,
        default: 'columns'
      },

      columnDropdown: {
        type: Array,
        required: true
      }
    },

    watch: {
      'tableColumns.length': function (newVal, oldVal) {
        if (newVal < oldVal) {
          return;
        }

        var self = this;
        this.$nextTick(function () {
          self.addColumnItemDrag();
        });
      }
    },

    inject: {
      templSetting: {
        default: ''
      }
    },

    data: function () {
      return {
        tableColumns: this.setting[this.columnField],
        dragId: null,
        id: SysUtil.getId()
      };
    },

    mounted: function () {
      this.addColumnItemDrag();
    },

    methods: {
      addColumnItemDrag: function () {
        var columnItems = this.$refs.columnItem;
        var self = this;
        var $el = this.$el;
        for (var i = 0; i < columnItems.length; i++) {
          var columnItem = columnItems[i];
          if ($(columnItem).hasClass('ui-draggable')) {
            continue;
          }
          $(columnItem).draggable({
            cursor: "move",
            appendTo: $el,
            containment: "window",
            scope: `table_${this.id}`,
            helper: function (event) {
              var $item = $(event.target).parents('.column-setting-item-content');
              $item = $item.clone();
              var $helper = $('<div class="column-setting-item column-setting-item-hepler"></div>').append($item);
              return $helper;
            },
            handle: ".column-item-colNo",
            zIndex: 3000,
            cursorAt:{
              top:20
            },
            start: function () {
              self.dragId = $(this).parents('.column-setting-item').data('id');
              self.templSetting.hasDrag = true;
            },
            stop: function () {
              self.dragId = null;
              self.templSetting.hasDrag = false;
            }
          });

          $(columnItem).droppable({
            hoverClass: "drop-highlight",
            scope: `table_${this.id}`,
            drop: function () {
              var dragId = self.dragId;
              if (dragId === null) {
                return;
              }

              var dropId = $(this).parents('.column-setting-item').data('id');
              self.exchangeColumn(dragId, dropId);
            }
          });
        }

        var columnLines = this.$refs.columnLine;
        for (var i = 0; i < columnLines.length; i++) {
          var columnLine = columnLines[i];
          if ($(columnLine).hasClass('ui-draggable')) {
            continue;
          }

          $(columnLine).droppable({
            hoverClass: "drop-highlight",
            scope: `table_${this.id}`,
            accept: function () {
              var dropId = $(this).parents('.column-setting-item').data('id');
              var dragId = self.dragId;
              if (dragId === dropId) {
                return false;
              }

              var tableColumns = self.tableColumns;
              var dragIndex = _.findIndex(tableColumns, {
                id: dragId
              });
              var dropIndex = _.findIndex(tableColumns, {
                id: dropId
              });
              var dir = $(this).data('dir');
              if (dir === 'top') {
                return dragIndex !== dropIndex - 1;
              }

              return dragIndex !== dropIndex + 1;
            },
            drop: function () {
              var dragId = self.dragId;
              if (dragId === null) {
                return;
              }

              var dropId = $(this).parents('.column-setting-item').data('id');
              var dir = $(this).data('dir');
              self.moveColumn(dragId, dropId, dir);
            }
          })
        }
      },

      getColumnDropdown: function (tableColumn) {
        var columnDropdown = this.columnDropdown;
        var tableColumns = this.tableColumns;
        var fields = _.map(tableColumns, 'field');
        columnDropdown = _.filter(columnDropdown, function (obj) {
          return tableColumn.field === obj.field || fields.indexOf(obj.field) === -1;
        });
        return columnDropdown;
      },

      exchangeColumn: function (dragId, dropId) {
        var tableColumns = this.tableColumns;
        var dragIndex, dragColumn, dropIndex, dropColumn;
        var flag = 0;
        for (var i = 0; i < tableColumns.length; i++) {
          var tableColumn = tableColumns[i];
          var id = tableColumn.id;
          if (id === dragId) {
            flag++;
            dragIndex = i;
            dragColumn = tableColumn;
          } else if (id === dropId) {
            flag++;
            dropIndex = i;
            dropColumn = tableColumn;
          }
          if (flag >= 2) {
            break;
          }
        }

        this.$set(tableColumns, dragIndex, dropColumn);
        this.$set(tableColumns, dropIndex, dragColumn);
      },

      moveColumn: function (dragId, dropId, dir) {
        var tableColumns = this.tableColumns;
        tableColumns = _.clone(tableColumns);
        var dragColumn = _.remove(tableColumns, function (column) {
          return column.id === dragId;
        });
        var dropIndex = _.findIndex(tableColumns, {
          id: dropId
        });
        dragColumn = dragColumn[0];
        if (dir === 'bottom') {
          dropIndex++;
        }
        tableColumns.splice(dropIndex, 0, dragColumn);
        this.tableColumns = tableColumns;
        this.setting[this.columnField] = tableColumns;
      },

      delColumn: function (id) {
        var tableColumns = this.tableColumns;
        if (tableColumns.length <= 1) {
          this.$alert('表格至少设置一列，因此不能删除', '信息');
          return;
        }
        var index = _.findIndex(tableColumns, {
          id: id
        });
        if (index === -1) {
          return;
        }
        tableColumns.splice(index, 1);
      },

      addColumn: function () {
        var tableColumns = this.tableColumns;
        var column = {
          id: SysUtil.getId(),
          label: '',
          field: '',
          width: undefined,
          hasSort: false,
          canSort: false
        };
        tableColumns.push(column);
      },

      fieldChange: function (tableColumn) {
        var field = tableColumn.field;
        var columnDropdown = this.columnDropdown;
        var column = _.find(columnDropdown, {
          field: field
        });

        var canSort = false;
        if (column !== undefined && !column.noUsedSort) {
          canSort = true;
        }
        tableColumn.canSort = canSort;
      }
    },

    template: template
  };
}();